<?php
namespace core\log;
/**
 * 本地化调试输出到文件
 */
class File{
    
    protected $config = [
        'time_format' => ' c ',
        'single'      => false,
        'file_size'   => 2097152,
        'path'        => '',
        'apart_level' => [],
    ];

    protected $writed = [];
    private $iscli = false;

    // 实例化并传入参数
    public function __construct($config = []){
        $this->iscli = PHP_SAPI == 'cli';
        if (is_array($config)) {
            $this->config = array_merge($this->config, $config);
        }
    }

    /**
     * 日志写入接口
     * @access public
     * @param array $log 日志信息
     * @return bool
     */
    public function save(array $log = []){
        if ($this->config['single']) {
            $destination = $this->config['path'] . 'single.log';
        } else {
            $cli         = $this->iscli ? '_cli' : '';
            $destination = $this->config['path'] . date('Ym') . DIRECTORY_SEPARATOR . date('d') . $cli . '.log';
        }

        $path = dirname($destination);
        !is_dir($path) && mkdir($path, 0775, true);

        $info = '';
        foreach ($log as $type => $val) {
            $level = '';
            if( $val['level']){
                $type = $val['level'];
                if (!is_string($val['data'])) {
                    $val['data'] = var_export(serialize($val['data']), true);
                }
                $emask  = $val['emask'] != $type ? '[ '. $val['emask'] .' ] ' : '';
                $level .= '[ ' . $type . ' ] '. $emask . $val['data'] . "\r\n";
            }else{
                foreach ($val as $msg) {
                    if (!is_string($msg)) {
                        $msg = var_export(serialize($msg), true);
                    }
                    $level .= '[ ' . $type . ' ] ' . $msg . "\r\n";
                }
            }
            
            if (in_array($type, $this->config['apart_level'])) {
                // 独立记录的日志级别
                if ($this->config['single']) {
                    $filename = $path . DIRECTORY_SEPARATOR . $type . '.log';
                } else {
                    $filename = $path . DIRECTORY_SEPARATOR . date('d') . '_' . $type . $cli . '.log';
                }
                $this->write($level, $filename, true);
            } else {
                $info .= $level;
            }
        }
        if ($info) {
            return $this->write($info, $destination);
        }
        return true;
    }
    

    protected function write($message, $destination, $apart = false){
        //检测日志文件大小，超过配置大小则备份日志文件重新生成
        if (is_file($destination) && floor($this->config['file_size']) <= filesize($destination)) {
            rename($destination, dirname($destination) . DIRECTORY_SEPARATOR . time() . '-' . basename($destination));
            $this->writed[$destination] = false;
        }

        if (empty($this->writed[$destination]) && !$this->iscli) {
                // 获取基本信息
                if (isset($_SERVER['HTTP_HOST'])) {
                    $current_uri = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
                } else {
                    $current_uri = "cmd:" . implode(' ', $_SERVER['argv']);
                }
            $now     = date($this->config['time_format']);
            $ip      = app()->request->ip();
            $method  = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'CLI';
            $uri     = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
            $host    = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '';
            $message = "---------------------------------------------------------------\r\n[{$now}] {$ip} {$method} {$host}{$uri}\r\n" . $message;
            $this->writed[$destination] = true;
        }
        if ($this->iscli) {
            $now     = date($this->config['time_format']);
            $message = "[{$now}]" . $message;
        }
        return error_log($message, 3, $destination);
    }

}
